package com.uusee.crawler.dbwriter;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.uusee.crawler.framework.Processor;
import com.uusee.crawler.model.CrawlURI;
import com.uusee.framework.bo.UniversalBo;
import com.uusee.framework.util.query.CriteriaInfo;
import com.uusee.shipshape.bk.model.Baike;
import com.uusee.shipshape.bk.model.BaikeImage;

public class BaikeImageDbWriter extends Processor {
	private static Log log = LogFactory.getLog(BaikeImageDbWriter.class);
	private UniversalBo universalBo;
	
	public void setUniversalBo(UniversalBo universalBo) {
		this.universalBo = universalBo;
	}

	protected void innerProcess(CrawlURI crawlURI) {
		BaikeImage baikeImage = (BaikeImage) crawlURI.getModel();
		Baike baike = baikeImage.getBaike();
		try {
			BaikeImage oldbaikeImage = getOldBaikeImage(baikeImage);
			if (oldbaikeImage!=null) {
				oldbaikeImage.setHeight(baikeImage.getHeight());
				oldbaikeImage.setWidth(baikeImage.getWidth());
				oldbaikeImage.setUpdateUser(baikeImage.getUpdateUser());
				oldbaikeImage.setUpdateDate(baikeImage.getUpdateDate());
				universalBo.doUpdate(oldbaikeImage);
				log.info(baikeImage.getOriImageUri() + "-更新百科图片。");
			} else {
				baike = getBaikeByOriIdAndSourceSite(baike);
				if (baike!=null) {
					baikeImage.setBaike(baike);
					universalBo.doSave(baikeImage);
					log.info(baikeImage.getOriImageUri() + "-增加百科图片。");
				}
			}

		} catch (Exception e) {
			log.error(baikeImage.getOriImageUri() + "-DB时发生错误。", e);
		}
	}

	private boolean isExist(BaikeImage bi) {
		CriteriaInfo ci = new CriteriaInfo();
		ci.eq("oriImageUri", bi.getOriImageUri());
		int count = universalBo.getCountByCriteriaInfo(BaikeImage.class, ci);
		if (count > 0) {
			return true;
		} else {
			return false;
		}
	}
	
	private BaikeImage getOldBaikeImage(BaikeImage bi) {
		CriteriaInfo ci = new CriteriaInfo();
		ci.eq("oriImageUri", bi.getOriImageUri());
		List<BaikeImage> baikeImageList = universalBo.getEntitiesByCriteriaInfo(BaikeImage.class, ci);
		if (baikeImageList.size() > 0) {
			return baikeImageList.get(0);
		} else {
			return null;
		}
	}

	private Baike getBaikeByOriIdAndSourceSite(Baike baike) {
		Baike oldBaike = null;
		String oriId = baike.getOriId();
		String sourceSite = baike.getSourceSite();

		CriteriaInfo ci = new CriteriaInfo();
		ci.eq("sourceSite", sourceSite);
		ci.eq("oriId", oriId);
		List<Baike> baikeList = universalBo.getEntitiesByCriteriaInfo(Baike.class, ci);
		if (baikeList != null && baikeList.size() == 1) {
			oldBaike = baikeList.get(0);
		}
		return oldBaike;
	}
}
